package softwareengineering_lab456;

import entity.Product;
import java.awt.Rectangle;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Background_JFrame extends JFrame {

    private static BasicConnectionSQL linktoSQL;
    private static final int posX = 183;
    private static final int posY = 20;
    private static final int screenWidth = 1000;
    private static final int screenHeight = 529;
    private MenuButton[] menubutton = new MenuButton[6];

    public Background_JFrame() {
        super();
        linktoSQL = new BasicConnectionSQL();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initialize();
        setLayout(null);
        this.setBounds(posX, posY, screenWidth, screenHeight);
        this.setVisible(true);
        this.setResizable(false);
    }

    private void initialize() {
        setRootPanel();
        setLayeredPanel();
        setContentPanel();
    }

    private void setRootPanel() {
        this.getRootPane().setVisible(true);
        this.getRootPane().add(BackgroundFigure(".\\img\\world.jpg"), 2);
    }

    private JLabel BackgroundFigure(String path) {
        ImageIcon icon_background = new ImageIcon(path);
        JLabel jlabel_background = new JLabel(icon_background);
        jlabel_background.setBounds(new Rectangle(0, 0, screenWidth, screenHeight));
        return jlabel_background;
    }

    private void setLayeredPanel() {
        this.getLayeredPane().setOpaque(false);
        this.getLayeredPane().setVisible(true);
        JPanel buttonPanel = new JPanel();
        this.getLayeredPane().add(buttonPanel, 0);
        setMenuButton(buttonPanel);
    }

    private void setContentPanel() {
        ((JPanel) (getContentPane())).setOpaque(false);
        JPanel LoginPanel = new JPanel();
        LoginPanel.setOpaque(false);
        this.getContentPane().add(LoginPanel);
        LoginPanel.setLayout(null);
        LoginPanel.setBounds(180, 40, 240, 150);
        LoginScreen(LoginPanel);
    }

    private void setMenuButton(JPanel parentPanel) {
        parentPanel.setOpaque(false);
        parentPanel.setLayout(null);
        parentPanel.setBounds(0, 0, screenWidth, screenHeight);
        menubutton[0] = new MenuButton("designer", new ImageIcon(".\\img\\designers.gif"));
        parentPanel.add(menubutton[0], 0);
        parentPanel.setVisible(true);
    }

    private void LoginScreen(JPanel loginPanel) {

        final JTextField username_text = new JTextField("username ");
        final JPasswordField password_text = new JPasswordField("password ");

        JLabel userNameLabel = new JLabel("UserName :");
        JLabel passWordLabel = new JLabel("PassWord :");
        username_text.addMouseListener(new LoginTextListener());
        password_text.addMouseListener(new LoginTextListener());

        username_text.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent fe) {
                if (username_text.getText().equalsIgnoreCase("username ")) {
                    username_text.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent fe) {
            }
        });
        password_text.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent fe) {
                if (password_text.getText().equalsIgnoreCase("password ")) {
                    password_text.setText("");
                }
            }

            @Override
            public void focusLost(FocusEvent fe) {
            }
        });

        password_text.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent ke) {
            }

            @Override
            public void keyPressed(KeyEvent ke) {
                if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    boolean passwordCorrect = false;
                    System.out.println();
                    try {
                        passwordCorrect = Background_JFrame.checkPassWord(username_text.getText(), password_text.getText());
                    } catch (Exception ex) {
                        Logger.getLogger(Background_JFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    System.out.println(passwordCorrect);
                    if (passwordCorrect) {
                        try {
                            showUserScreen();
                        } catch (Exception ex) {
                            Logger.getLogger(Background_JFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }

            }

            @Override
            public void keyReleased(KeyEvent ke) {
            }
        });

        username_text.setBounds(80, 60, 160, 25);
        password_text.setBounds(80, 90, 160, 25);
        userNameLabel.setBounds(10, 60, 70, 25);
        passWordLabel.setBounds(10, 90, 70, 25);

        loginPanel.add(username_text, 0);
        loginPanel.add(password_text, 1);
        loginPanel.add(userNameLabel, 2);
        loginPanel.add(passWordLabel, 3);

        JButton reset = new JButton("reset");
        JButton comfirm = new JButton("enter");
        reset.addMouseListener(new LoginButtonListener(username_text, password_text, reset, this));
        comfirm.addMouseListener(new LoginButtonListener(username_text, password_text, comfirm, this));
        loginPanel.add(comfirm, 4);
        loginPanel.add(reset, 5);
        comfirm.setBounds(160, 120, 80, 25);
        reset.setBounds(80, 120, 80, 25);

    }

    public static boolean checkPassWord(String username, String password) throws Exception {
        String realPass = linktoSQL.getPWD_mySQL(username);
        System.out.println("real pass:" + realPass);
        if (realPass == null) {
            return false;
        } else if (password.equals(realPass)) {
            return true;
        }
        return false;
    }

    public void showUserScreen() throws Exception {
        for (int i = 0; i < this.getContentPane().getComponentCount(); i++) {
            this.getContentPane().remove(i);
        }

        int posID_X = 80;
        int posName_X = 210;
        int posPrice_X = 330;
        int posType_X = 480;
        int posCount_X = 630;
        int LabelH = 30;
        int LabelW = 80;
        int Y_Position = 60;

        JPanel productlistScreen = new JPanel();
        productlistScreen.setLayout(null);
        productlistScreen.setBounds(0, 0, screenWidth, screenHeight);
        productlistScreen.setVisible(true);
        productlistScreen.setOpaque(false);
        this.getContentPane().add(productlistScreen, 0);

        JLabel productID = new JLabel("    productID                     Name                                      Price                                        Type                                         Count");
        productlistScreen.add(productID, 0);
        productID.setBounds(posID_X, Y_Position, 1500, LabelH);
        productID.setVisible(true);

        repaint();
        linktoSQL.getConn();
        ArrayList<Product> productList = linktoSQL.findAllProduct();
        for (int i = 0; i < productList.size(); i++) {
            String id = String.valueOf(productList.get(i).getId());
            JLabel productid = new JLabel("            " + id);
            productlistScreen.add(productid, i + 1);
            productid.setBounds(posID_X, Y_Position + 30 * (i + 1), LabelW, LabelH);

            String name = String.valueOf(productList.get(i).getName());
            JLabel productname = new JLabel(name);
            productlistScreen.add(productname, i + 2);
            productname.setBounds(posName_X, Y_Position + 30 * (i + 1), LabelW, LabelH);

            String price = String.valueOf(productList.get(i).getPrice());
            JLabel productprice = new JLabel("          " + price);
            productlistScreen.add(productprice, i + 3);
            productprice.setBounds(posPrice_X, Y_Position + 30 * (i + 1), LabelW, LabelH);

            String type = String.valueOf(productList.get(i).getType());
            JLabel producttype = new JLabel("          " + type);
            productlistScreen.add(producttype, i + 3);
            producttype.setBounds(posType_X, Y_Position + 30 * (i + 1), LabelW, LabelH);

            String quantity = String.valueOf(productList.get(i).getQuantity());
            JLabel productquantity = new JLabel("          " + quantity);

            productlistScreen.add(productquantity, i + 3);
            productquantity.setBounds(posCount_X, Y_Position + 30 * (i + 1), LabelW, LabelH);

            JButton buyButton = new JButton(" buy 1");
            buyButton.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    System.out.println("DONE");
                }

                @Override
                public void mousePressed(MouseEvent me) {
                }

                @Override
                public void mouseReleased(MouseEvent me) {
                }

                @Override
                public void mouseEntered(MouseEvent me) {
                }

                @Override
                public void mouseExited(MouseEvent me) {
                }
            });
            final int productQuantity = Integer.valueOf(quantity);
            final int idNum = i + 1;
            final JLabel proQuan = productquantity;
            productlistScreen.add(buyButton);

            buyButton.addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent me) {
                    String[] par = {String.valueOf(idNum)};
                    try {
                        if (linktoSQL.getQuantity(idNum) > 0) {

                            linktoSQL.executeSQL(" update product set quantity=quantity-1 where id=?", par);
                            proQuan.setText("         " + String.valueOf(linktoSQL.getQuantity(idNum)));
                            proQuan.setBounds(630, 60 + 30 * idNum, 80, 30);
                        } else {
                            JOptionPane.showMessageDialog(null, "---> Out of Stock");
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(Background_JFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

                @Override
                public void mousePressed(MouseEvent me) {
                }

                @Override
                public void mouseReleased(MouseEvent me) {
                }

                @Override
                public void mouseEntered(MouseEvent me) {
                }

                @Override
                public void mouseExited(MouseEvent me) {
                }
            });
            buyButton.setBounds(posCount_X + 150, Y_Position + 30 * (i + 1) + 5, LabelW, LabelH - 10);

        }

        repaint();
    }
}

class LoginTextListener implements MouseListener {

    @Override
    public void mouseClicked(MouseEvent me) {
    }

    @Override
    public void mousePressed(MouseEvent me) {
        JTextField jf = (JTextField) me.getSource();
        if (jf.getText().equalsIgnoreCase("username ") || jf.getText().equalsIgnoreCase("password ")) {
            jf.setText("");
        }
    }

    @Override
    public void mouseReleased(MouseEvent me) {
    }

    @Override
    public void mouseEntered(MouseEvent me) {
    }

    @Override
    public void mouseExited(MouseEvent me) {
    }
}

class LoginButtonListener implements MouseListener {

    JButton parentButton;
    JTextField usernameTextField;
    JTextField passwordTextField;
    Background_JFrame parentFrame;

    LoginButtonListener(JTextField username, JTextField password, JButton parentButton, Background_JFrame parentFrame) {
        this.usernameTextField = username;
        this.passwordTextField = password;
        this.parentButton = parentButton;
        this.parentFrame = parentFrame;
    }

    @Override
    public void mouseClicked(MouseEvent me) {
        switch (parentButton.getText()) {
            case "reset": {

                usernameTextField.setText("");

                passwordTextField.setText("");
            }
            break;
            case "enter": {
                boolean passwordCorrect = false;
                System.out.println();
                try {
                    passwordCorrect = Background_JFrame.checkPassWord(usernameTextField.getText(), passwordTextField.getText());
                } catch (Exception ex) {
                    Logger.getLogger(LoginButtonListener.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println(passwordCorrect);
                if (passwordCorrect) {
                    try {
                        parentFrame.showUserScreen();
                    } catch (Exception ex) {
                        Logger.getLogger(LoginButtonListener.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
            break;
        }

    }

    @Override
    public void mousePressed(MouseEvent me) {
    }

    @Override
    public void mouseReleased(MouseEvent me) {
    }

    @Override
    public void mouseEntered(MouseEvent me) {
    }

    @Override
    public void mouseExited(MouseEvent me) {
    }
}

class MenuButton extends JButton implements MouseListener {

    MenuButton(String s, Icon icon) {
        super(s, icon);
        this.setBounds(0, 469, 120, 26);
        this.setVisible(true);
        this.addMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent me) {
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mousePressed(MouseEvent me) {
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseReleased(MouseEvent me) {
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseEntered(MouseEvent me) {
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseExited(MouseEvent me) {
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
